#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from camera import *
from trt_eng import TrtSSD
from counter import Counter
from time import time,sleep
from mplayer import Player
import RPi.GPIO as GPIO
import asyncio
from remotectl import RemoteCtl
import os
import sys
from update import update
import logging
logging.basicConfig(level = logging.ERROR)
p1=os.getcwd()
p2=os.path.dirname(__file__)
p3=p1
if len(p2)>0:
    if p2[0]!='/':
        p3=os.path.join(p1,p2)
    else:
        p3=p2
    os.chdir(p3)
curdir=p3
del(p1)
del(p2)
del(p3)
sysupdated=False
output_pin =  16
input_pin = 7
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(output_pin, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(input_pin,GPIO.IN)

colors=[(0,0,0),
        (255,0,0),
        (0,255,0),
        (0,0,255),
        (0,255,255)
                ]

def drawboxs(img,boxes,clss):
    for i in range(len(boxes)):
        x1,y1,x2,y2=boxes[i]
        rectangle(img,(x1,y1),(x2,y2),colors[clss[i]])

async def main(remotectl,loop):
    STAT_PUSH=20
    STAT_PUSH15=10
    STAT_RUN=0
    STAT_ALERM=1
    KEY_A1=20
    KEY_B2=16
    KEY_ON=11
    KEY_OFF=5
    if 1:
        global sysupdated
        global output_pin
        global input_pin
        global curdir
        cnt=Counter()
        pretime=time()
        player=Player()
        cap=Camera(0,640,480)
        trt=TrtSSD("ssd_mobilenet_v2_bike",videoCapture=cap)
        state=STAT_RUN
        worktime=time()
        if len(sys.argv)>1:
            player.play("mp3/08.mp3")
        else:
            player.play("mp3/09.mp3")
    aconf=0.5
    aconfdelay=time()
    aconf_needplay=False
    if  os.path.exists("config"):
        with open("config",'r') as f:
            aconf=float(f.read())
    predetect=False
    ifn=0
    while 1:
        key=await remotectl.key(False)
        if key:print(key)
        img,boxs,_,clss=trt.getresult(1-aconf)
        idx=cnt.record(clss)
        #采集图片,基准是当检测不到车子的那一刻,采集一张图片
        if  (1 in clss or 2 in clss  or  3 in clss) and (not predetect):
            predetect=True
            imwrite("./jpg/S{:05d}.jpg".format(ifn),img,[IMWRITE_JPEG_QUALITY,100])
            ifn+=1
            if ifn>8000: ifn=0
        else:
            if predetect:
                predetect=False
                imwrite("./jpg/E{:05d}.jpg".format(ifn),img,[IMWRITE_JPEG_QUALITY,100])
                ifn+=1
                if ifn>8000: ifn=0
        drawboxs(img,boxs,clss)
        imshow("EBike  Monitor",img)
        k=waitKey(1)
        if k==27:
            break
        stime=max(0.05-time()+pretime,0)
        pretime=time()
        # if stime<0.002:
        #     print(stime)
        await asyncio.sleep(stime)
        #识别率调整
        if state==STAT_PUSH and key in [KEY_A1,KEY_B2]:
            if key==KEY_A1:
                aconf=aconf+0.1
                if aconf>=0.99: aconf=0.9
            if key==KEY_B2:
                aconf=aconf-0.1
                if aconf<0:aconf=0
            with open("config",'w') as f:
                f.write(str(round(aconf,1)))
            aconfdelay=time()
            aconf_needplay=True
            inti=round((aconf+0.1)*10)
            intf=str(inti)
            playfile=f"mp3/s{intf}.mp3"
        if time()-aconfdelay>1 and aconf_needplay:
            player.play(playfile)
            aconf_needplay=False

        if state==STAT_PUSH15:  #系统暂停15分钟
            if time()-worktime<60*15 and key!=KEY_ON :
                continue
            elif key != KEY_ON:
                state=STAT_RUN
        elif state==STAT_PUSH:#系统暂停工作,等待恢复
            if key!=KEY_ON:      #恢复系统工作
                continue

        if key==KEY_ON and state in [STAT_PUSH15,STAT_PUSH]:          #系统恢复工作
            player.play("mp3/05.mp3")
            state=STAT_RUN 

        if key==KEY_A1:         #系统暂停15分钟
            player.play("mp3/03.mp3")
            worktime=time()
            state=STAT_PUSH15
            #cancel alerm 
            GPIO.output(output_pin,GPIO.LOW)
            continue
        if key==KEY_B2:         #系统升级
            destroyWindow("EBike  Monitor")
            player.play("mp3/02.mp3")
            #cancel Alerm
            GPIO.output(output_pin,GPIO.LOW)
            if update(curdir):
                sysupdated=True
                player.play("mp3/07.mp3")
                logging.info("升级成功.")
                break
            else:
                player.play("mp3/10.mp3")
        if key==KEY_OFF:         #系统暂停
            player.play("mp3/04.mp3")
            state=STAT_PUSH
            #cancel alerm
            GPIO.output(output_pin,GPIO.LOW)
            continue
        if GPIO.input(input_pin):
            continue
        if state==STAT_RUN:
            b,c,d,_=cnt.sum(1,idx)
            if (b>10 or c>10): #and d==0:
                state=STAT_ALERM
                player.play("mp3/01.mp3")
                #alerm start
                GPIO.output(output_pin,GPIO.HIGH)
                logging.info("alerming")
        elif state==STAT_ALERM:
            b,c,d,_=cnt.sum(5,idx)
            if (b==0 and c==0):
                state=STAT_RUN
                #alerm cancel
                GPIO.output(output_pin,GPIO.LOW)
                player.play("mp3/06.mp3")
                logging.info("alerm cancel")
    GPIO.output(output_pin,GPIO.LOW)
    trt.stop()
    cap.stop()
    player.stop()
    remotectl.close()
    GPIO.cleanup()
    loop.stop()

if __name__ == "__main__":
    loop=asyncio.get_event_loop()
    ser=RemoteCtl("/dev/ttyTHS1",loop)
    asyncio.ensure_future(main(ser,loop))
    try:
        loop.run_forever()
    finally:
        loop.run_until_complete(loop.shutdown_asyncgens())
        if sysupdated:
            os.popen("sh start.sh 123")
        logging.info("sysExited")
        loop.close()
